<!--
 * @Description: 实际施工进度
 * @Author: wang_k
 * @Date: 2025-08-18 11:33:17
 * @LastEditTime: 2025-08-19 19:27:27
 * @FilePath: /note/src/views/Ceshi/components/xxx.vue
-->
<template>
  <div class="rock_chart">
    <!-- <SecondTitle title="实际施工进度" style="margin-bottom: 10px">
			<div class="title_right_content">
				<div class="right_title_info">
					<div class="legend">
						<div
							class="legend-item"
							v-for="(item, index) in legendData"
							:key="index"
						>
							<span
								class="legend-dot"
								:style="{
									background: item.color
								}"
							></span>
							<span class="legend-text">{{ item.text }}</span>
						</div>
						施工部位：开挖支护
					</div>
				</div>
				<img src="~@/assets/img/Cbe/narrow.png" alt="" @click="zoomHandle" />
			</div>
		</SecondTitle> -->
    <div class="trend_chart_box">
      <div class="chart_box_left">
        <div
          class="panel-item"
          v-for="item in panelData"
          :key="item.label"
          :style="`background:${item.color}`"
        >
          <div>{{ item.label }}</div>
          <div>{{ item.value }}m</div>
        </div>
      </div>
      <div class="chart_box_right">
        <div class="progress-box">
          <div class="progress-content">
            <div
              class="progress-history"
              :style="{
                width: history_width + '%',
              }"
            >
              历史态势
            </div>
            <div
              class="progress-future"
              :style="{
                width: 100 - history_width + '%',
              }"
            >
              未来态势
            </div>
          </div>
          <div class="progress-scale">
            <div
              class="progress-scale-item"
              v-for="(item, index) in xData"
              :key="item.value"
              :style="{
                width: item.width + '%',
              }"
            >
              <div class="progress-scale-line" v-show="index !== 0"></div>
              <div class="progress-scale-son" v-show="index !== 0">
                {{ dayFormat(item.value) }}
              </div>
            </div>
          </div>
          <div
            class="marking-line"
            :style="{
              left: currentPosition + '%',
            }"
          >
            <span class="line-row1">{{ markingData.date }}</span>
            <span class="line-row2">{{ markingData.meter }}</span>
          </div>
        </div>
        <div class="play-button" @click="handlePlay">
          <span v-if="!isPlaying">播放</span>
          <span v-else>暂停</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import SecondTitle from './RightInfoContents/SecondTitle.vue'
export default {
  name: 'ConstructionProgressChart',
  components: {
    // SecondTitle
  },
  props: {},
  data() {
    return {
      legendData: [
        {
          color: '#78CD78',
          text: '已完成',
        },
        {
          color: '#BFBFBF',
          text: '未开始',
        },
      ],
      panelData: [
        {
          label: '设计长度',
          value: '1530',
          color:
            'linear-gradient(284deg,rgba(0, 107, 237, 0) 3%,rgba(0, 107, 237, 0.15) 95%)',
        },
        {
          label: '2024年实际完成',
          value: '1530',
          color:
            'linear-gradient(284deg, rgba(149, 125, 243, 0) 3%, rgba(149, 125, 243, 0.15) 95%)',
        },
        {
          label: '2025年计划完成',
          value: '1530',
          color:
            'linear-gradient(284deg, rgba(249, 175, 85, 0) 3%, rgba(249, 175, 85, 0.15) 95%)',
        },
      ],
      markingData: {
        date: '2024-07-03',
        meter: '123m',
      },
      initcurrentPosition: 0,
      currentPosition: 20,
      history_width: 40,
      isPlaying: false,
      animationInterval: null,
      animationFrameId: null,

      playbackSpeed: 2, // 播放速度控制
      playEndDate:'2024-09-01',
      startTime: null,
      elapsedTime: 0,
    };
  },
  computed: {
    xData() {
      // debugger;
      let res = [];
      let dayArr = this.generateMonthlyFirstDays();
      function calculatePercentage(part, total, decimalPlaces = 2) {
        // 处理除数为0的情况
        if (total === 0) {
          return '0';
        }
        // 计算百分比并四舍五入
        const percentage = (part / total) * 100;
        const rounded = percentage.toFixed(decimalPlaces);

        // 返回带百分号的字符串
        return `${rounded}`;
      }
      const width = calculatePercentage(1, dayArr.length);
      res = dayArr.map((item) => {
        return {
          value: item,
          width: width,
        };
      });
      console.log(res, 'xData');

      return res;
    },
    totalMonths() {
      return this.xData.length;
    },
    totalDuration() {
      return this.totalMonths * 5000; // 总时长 = 月数 * 5000毫秒（5秒/月）
    },
  },
  watch: {},
  created() {
    this.calculateMarkerPosition();
  },
  mounted() {
    // window.eventHub.$on('onProgressChange', this.handlerProgressChange)
  },
  methods: {
    dayFormat(value) {
      return this.$dayjs(value).format('MM-DD');
      // return this.$dayjs(value).format('YYYY-MM-DD')
    },
    calculateMarkerPosition() {
      // 1. 获取时间轴数据
      const timeline = this.xData.map((item) => item.value);

      // 2. 找到开始日期（第一个点）
      const startDate = timeline[0];

      // 3. 计算时间总跨度（毫秒）
      const startTime = this.$dayjs(startDate).valueOf();
      const endTime = this.$dayjs(timeline[timeline.length - 1]).valueOf();
      const totalDuration = endTime - startTime;

      // 4. 计算目标日期距离开始日期的时间
      const targetTime = this.$dayjs(this.markingData.date).valueOf();
      const elapsedTime = targetTime - startTime;

      // 5. 计算时间比例 (0-1)
      const timeRatio = Math.min(1, Math.max(0, elapsedTime / totalDuration));
      console.log(timeRatio);

      // 6. 转换为进度条位置
      this.currentPosition = timeRatio * 100;
      this.initcurrentPosition = timeRatio * 100;

      console.log(`标记线位置计算完成: ${this.currentPosition.toFixed(2)}%`);

      // 7. 更新标记数据
      // this.updateMarkingData();
    },
    handlePlay() {
      if (this.isPlaying) {
        this.pauseAnimation();
      } else {
        this.startAnimation();
      }
      this.isPlaying = !this.isPlaying;
    },

    startAnimation() {
      if (this.animationInterval) return;
      console.log(this.currentPosition);

      // 如果已经到达终点，重新开始
      if (this.currentPosition + this.initcurrentPosition >= 100) {
        this.currentPosition = this.initcurrentPosition;
        this.elapsedTime = 0;
      }

      this.startTime =  Date.now() - this.elapsedTime;
      // this.startTime = this.$dayjs(this.playEndDate).valueOf() - this.elapsedTime;

      const animate = () => {
        const now = Date.now();
        // const now = this.$dayjs(this.playEndDate).valueOf();
        const elapsed = now - this.startTime;
        this.elapsedTime = elapsed;

        // 计算当前进度 (0-1)
        const progress = Math.min(1, elapsed / this.totalDuration);

        // 计算当前位置 (20% 到 100%)
        this.currentPosition =
          this.initcurrentPosition +
          progress * (100 - this.initcurrentPosition);

        // 更新标记数据
        this.updateMarkingData();
        console.log(progress, 'progress');

        // 继续动画或结束
        if (progress < 1) {
          this.animationInterval = requestAnimationFrame(animate);
        } else {
          this.isPlaying = false;
          this.animationInterval = null;
        }
      };

      this.animationInterval = requestAnimationFrame(animate);
    },

    pauseAnimation() {
      if (this.animationInterval) {
        cancelAnimationFrame(this.animationInterval);
        this.animationInterval = null;
      }
    },

    updateMarkingData() {
      // 计算当前点索引
      const totalPoints = this.xData.length;
      const pointIndex = Math.min(
        totalPoints - 1,
        Math.floor(((this.currentPosition - 20) / 80) * totalPoints),
      );

      // 更新日期
      if (this.xData[pointIndex]) {
        // this.markingData.date = this.dayFormat(this.xData[pointIndex].value);
        this.markingData.date = '2024-07-12';
      }

      // 更新米数 (示例计算)
      const totalMeters = 1530;
      const currentMeters = Math.floor(
        (totalMeters * (this.currentPosition - 20)) / 80,
      );
      this.markingData.meter = `${1231}m`;
    },
    zoomHandle() {
      // window.eventHub.$emit('onProgressChange', { isShow: false })
    },
    generateMonthlyFirstDays(inputDate = '2024-07-05') {
      // 1. 定义起始日期（2024年7月1日）和终止日期（当前月第一天）
      const start = this.$dayjs(inputDate).startOf('month'); // 起始月第一天
      const end = this.$dayjs().startOf('month'); // 当前月第一天（避免生成未来月）
      const firstDayList = [];
      let current = start; // 循环用的当前日期

      // 2. 循环：从起始月到当前月，逐个添加每月第一天
      while (current.isBefore(end) || current.isSame(end)) {
        // 格式化为 "YYYY-MM-DD" 字符串并推入数组
        firstDayList.push(current.format('YYYY-MM-DD'));
        // 月份加1，自动处理跨年（如12月+1 → 次年1月）
        current = current.add(1, 'month');
      }
      return firstDayList;
    },
  },
  beforeDestroy() {
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
    }
    // window.eventHub.$on('onProgressChange', this.handlerProgressChange)
  },
};
</script>

<style scoped>
.rock_chart {
  position: absolute;
  bottom: 74px;
  left: 23%;
  width: 55%;
  height: 25%;
  /* // width: 100%;
	// height: 100%; */
  padding: 15px;
  border-width: 3px;
  border-style: solid;
  border-color: white;
  border-radius: 12px;
  background-color: #f4f7fa;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  /* // overflow-y: hidden; */
}

.title_right_content {
  display: flex;
  align-items: center;

  .right_title_info {
    margin-right: 15px;
    font-size: 12px;
    color: #666666;
  }

  img {
    width: 14px;
    height: 14px;
    cursor: pointer;
  }
}

.trend_chart_box {
  display: flex;
  /* // flex-direction: column; */
  justify-content: space-between;
  width: 100%;
  /* // height: 158px; */
  height: calc(100% - 30px);
  position: relative;
  .chart_box_left {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    width: 140px;
    .panel-item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: center;
      padding-left: 12px;
      width: 125px;
      height: 54px;
      font-size: 14px;
      border-radius: 4px;
      box-sizing: border-box;
      border: 1px solid rgba(0, 107, 237, 0.2);
    }
  }
  .chart_box_right {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    width: calc(100% - 165px);
    .progress-box {
      position: relative;
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 80%;
      justify-content: center;
    }
    .progress-content {
      display: flex;
      width: 100%;
      height: 20px;
      font-size: 12px;
      background: #999;
      border-radius: 20px;
      color: #fff;
      overflow: hidden;
    }
    .progress-history {
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(90deg, #97df97 0%, #63cb63 100%);
    }
    .progress-future {
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(270deg, #a1a1a1 0%, #bfbfbf 100%);
    }
    .progress-scale {
      display: flex;
      width: 100%;
      .progress-scale-item {
        position: relative;
        font-size: 12px;
        .progress-scale-line {
          width: 1px;
          height: 6px;
          background-color: #999;
        }
        .progress-scale-son {
          position: absolute;
          left: -20%;
        }
      }
    }
    .marking-line {
      position: absolute;
      top: 50%;
      bottom: 0;
      width: 0;
      height: 60%;
      border-left: 0.125rem solid #1890ff;
      transition: left 0.3s;
      z-index: 2;
      transform: translateY(-50%);
      color: #1890ff;
    }
    .marking-line:after {
      content: ''; /* 伪元素必须有 content 属性 */
      position: absolute;
      top: -5px;
      right: -4px;

      /* 三角样式 */
      width: 0;
      height: 0;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
      border-top: 5px solid #1890ff; /* 上边框有颜色，形成向下三角 */
    }
    .line-row1 {
      font-size: 12px;
      width: 70px;
      display: inline-block;
      position: absolute;
      bottom: -20px;
      left: -35px;
    }
    .line-row2 {
      font-size: 12px;
      width: 70px;
      display: inline-block;
      position: absolute;
      top: -20px;
      left: -35px;
    }
  }
}

::v-deep .SecondTitle .title {
  font-weight: bold;
}

.legend {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 32px;
  gap: 16px;

  .legend-item {
    display: flex;
    align-items: center;
    gap: 4px;

    .legend-dot {
      width: 10px;
      height: 10px;
    }

    .legend-text {
      font-size: 12px;
      color: #666;
    }
  }
}
</style>
